package com.ytktt.study.week9.task3.rpcfx.lb;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 基于权重的负载均衡算法
 *
 * @author ytk
 */
public class WeightLoadBalancer implements LoadBalancer {

    private final Map<String, Integer> weightMapping;
    private final Random random = new Random();

    public WeightLoadBalancer(Map<String, Integer> weightMapping) {
        this.weightMapping = weightMapping;
    }

    @Override
    public String select(List<String> urls) {
        List<String> repeatEndpoints = new ArrayList<>();
        for (String endpoint : urls) {
            for (int i = 0; i < this.weightMapping.get(endpoint); i++) {
                repeatEndpoints.add(endpoint);
            }
        }
        int size = repeatEndpoints.size();
        return repeatEndpoints.get(this.random.nextInt(size));
    }
}
